package com.edu.udistrital.indexing.document;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.TermVector;

public class LearningDocument implements DocumentIndex {

	@Override
	public Document obtenerDocumento(File file) throws Exception {
		Document doc = new Document();
        
		FileInputStream fstream = null;
		DataInputStream in = null;
		BufferedReader br = null;
		StringBuilder strDocumento = null;
		
		try {
			fstream = new FileInputStream(file);
			in = new DataInputStream(fstream);
			br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			strDocumento = new StringBuilder();
			
	        String strLinea;
	        
	        while ((strLinea = br.readLine()) != null) {
	        	strDocumento.append(strLinea.replaceAll("[0-9]", "")+" ");
	        	
	        }
		}finally {
			br.close();
		}
		
		
//		doc.add(new Field("contenido", new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")), TermVector.YES));
		doc.add(new Field("contenido", strDocumento.toString(), Field.Store.YES, Field.Index.ANALYZED, TermVector.YES));
		doc.add(new Field("archivo", file.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
		doc.add(new Field("categoria", obtenerCategoria(file.getParent()), Field.Store.YES, Field.Index.NOT_ANALYZED));
		
		return doc;
	}
	
	private String obtenerCategoria(String parentFile) {
		String categoria;
		String separador = "";

		if(System.getProperty("os.name").equalsIgnoreCase("linux")){
			separador = System.getProperty("file.separator");
		}else {
			separador = "\\\\";
		}
		
		String[] parent = parentFile.split(separador);
		categoria = parent[parent.length-1];
		
		return categoria;
	}

}
